package com.bl.student.manager.interceptor;

import com.bl.student.common.utils.CommonUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by yujingyi on 2017/6/13.
 */
@Log4j2
public class RequestMappingInterceptor implements HandlerInterceptor {

    //before the actual handler will be executed
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler)
            throws Exception {


        long startTime = System.currentTimeMillis();
        request.setAttribute(CommonUtils.API_START_TIME, startTime);

        return true;
    }

    //after the handler is executed
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {
        long executeTime = System.currentTimeMillis() - getStartTime(request);

        // get request url
        String reqUri = getUri(request);

        log.info("request: {}, cost: {}", reqUri, executeTime);
    }

    @Override
    public void afterCompletion(HttpServletRequest arg0,
                                HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub

    }

    private long getStartTime(HttpServletRequest request) {
        return (Long)request.getAttribute(CommonUtils.API_START_TIME);
    }

    private String getUri(HttpServletRequest request) {
        return request.getRequestURI().replace(
                request.getContextPath(), "");
    }
}
